/**
 * Wails API 封装
 * 注意：需要先运行 wails dev 生成类型定义后才能正常使用
 */
import type { LoginResponse, LoginConfig } from '../types/api'

// 日志相关类型
export interface LogEntry {
  time: string
  level: string
  module: string
  message: string
  data?: Record<string, unknown>
}

export interface LogQuery {
  level?: string
  module?: string
  startTime?: string
  endTime?: string
  limit?: number
}

export interface LogResponse {
  logs: LogEntry[]
  total: number
}

// 声明 window.go 类型
declare global {
  interface Window {
    go?: {
      main?: {
        App?: {
          Login?: (loginId: string, loginKey: string) => Promise<LoginResponse>
          GetLoginConfig?: () => Promise<LoginConfig>
          SaveAppConfig?: (key: string, value: Record<string, unknown>) => Promise<void>
          GetAppConfig?: (key: string) => Promise<unknown>
          WriteLog?: (level: string, module: string, message: string, data?: Record<string, unknown>) => Promise<void>
          GetLogs?: (query: LogQuery) => Promise<LogResponse>
          ClearLogs?: () => Promise<void>
        }
      }
    }
  }
}

// 获取 Wails App 方法
function getAppMethods() {
  // 优先使用 window.go（运行时可用）
  if (window.go?.main?.App) {
    return window.go.main.App
  }
  
  // 如果 window.go 不存在，返回 null
  // 注意：运行 wails dev 后，window.go 会自动注入
  return null
}

export const wailsAPI = {
  /**
   * 登录验证
   */
  async login(loginId: string, loginKey: string): Promise<LoginResponse> {
    try {
      const app = getAppMethods()
      if (!app?.Login) {
        throw new Error('Login 方法未找到，请先运行 wails dev 生成类型定义')
      }
      const result = await app.Login(loginId, loginKey)
      return result as LoginResponse
    } catch (error) {
      throw new Error(`登录失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 获取登录配置
   */
  async getLoginConfig(): Promise<LoginConfig> {
    try {
      const app = getAppMethods()
      if (!app?.GetLoginConfig) {
        throw new Error('GetLoginConfig 方法未找到，请先运行 wails dev 生成类型定义')
      }
      const result = await app.GetLoginConfig()
      return result as LoginConfig
    } catch (error) {
      throw new Error(`获取登录配置失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 保存应用配置
   */
  async saveAppConfig(key: string, value: unknown): Promise<void> {
    try {
      const app = getAppMethods()
      if (!app?.SaveAppConfig) {
        throw new Error('SaveAppConfig 方法未找到，请先运行 wails dev 生成类型定义')
      }
      await app.SaveAppConfig(key, value as Record<string, unknown>)
    } catch (error) {
      throw new Error(`保存配置失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 获取应用配置
   */
  async getAppConfig(key: string): Promise<unknown> {
    try {
      const app = getAppMethods()
      if (!app?.GetAppConfig) {
        throw new Error('GetAppConfig 方法未找到，请先运行 wails dev 生成类型定义')
      }
      return await app.GetAppConfig(key)
    } catch (error) {
      throw new Error(`获取配置失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 写入日志
   */
  async writeLog(level: string, module: string, message: string, data?: Record<string, unknown>): Promise<void> {
    try {
      const app = getAppMethods()
      if (!app?.WriteLog) {
        throw new Error('WriteLog 方法未找到，请先运行 wails dev 生成类型定义')
      }
      await app.WriteLog(level, module, message, data)
    } catch (error) {
      console.error(`写入日志失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 获取日志
   */
  async getLogs(query: LogQuery): Promise<LogResponse> {
    try {
      const app = getAppMethods()
      if (!app?.GetLogs) {
        throw new Error('GetLogs 方法未找到，请先运行 wails dev 生成类型定义')
      }
      const result = await app.GetLogs(query)
      return result as LogResponse
    } catch (error) {
      throw new Error(`获取日志失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  },

  /**
   * 清空日志
   */
  async clearLogs(): Promise<void> {
    try {
      const app = getAppMethods()
      if (!app?.ClearLogs) {
        throw new Error('ClearLogs 方法未找到，请先运行 wails dev 生成类型定义')
      }
      await app.ClearLogs()
    } catch (error) {
      throw new Error(`清空日志失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }
}

